<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sa="http://www.w3.org/1999/xhtml" lang="">
<head>
    <meta charset="utf-8">
    <title>我的预约</title>
    <link rel="stylesheet" th:href="@{/pear/component/pear/css/pear.css}"/>
</head>
<body class="pear-container">
<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="">
            <div class="layui-form-item">
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">会议主题:</label>
                    <div class="layui-input-inline">
                        <input id="purpose" type="text" name="purpose" placeholder="请输入会议主题"
                               class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">开始日期:</label>
                    <div class="layui-input-inline">
                        <input type="text" name="reservationDate" id="beginDate"
                               placeholder="请选择日期" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">结束日期:</label>
                    <div class="layui-input-inline">
                        <input type="text" name="repeatEndDate" id="endDateDiv"
                               placeholder="请选择结束日期" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">时间:</label>
                    <div class="layui-input-inline">
                        <input type="text" name="timeFrame" id="timeFrame"
                               placeholder=" - " autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">类型</label>
                    <div class="layui-input-inline">
                        <select name="repeatType" id="repeatType" lay-filter="repeatType">
                            <option value="">请选择类型</option>
                            <option value="0">一次</option>
                            <option value="1">每天</option>
                            <option value="2">每个工作日</option>
                            <option value="3">每周的星期几</option>
                            <option value="4">每月的第几天</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">会议室</label>
                    <div class="layui-input-inline">
                        <select name="roomName" id="meeting" lay-filter="meeting">
                            <option value="-1">请选择</option>
                            <!-- 动态加载会议室选项 -->
                        </select>
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <button class="layui-btn layui-btn-md " lay-submit sa:hasPermission="reservation_select"
                            lay-filter="myReservation-query">
                        <i class="layui-icon layui-icon-search"></i>
                        查询
                    </button>
                    <button type="reset" class="layui-btn layui-btn-md" id="resetBtn">
                        <i class="layui-icon layui-icon-refresh"></i>
                        重置
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
<div class="layui-card">
    <div class="layui-card-body">
        <table id="myReservation-table" lay-filter="myReservation-table"></table>
    </div>
</div>

<script type="text/html" id="myReservation-toolbar">
    <button class="layui-btn layui-btn-danger layui-btn-md" sa:hasPermission="reservation_batchRemove"
            lay-event="batchDelete">
        <i class="layui-icon layui-icon-delete"></i>
        批量删除
    </button>
    <button class="layui-btn layui-bg-blue layui-btn-md" lay-event="refresh">
        <i class="layui-icon layui-icon-refresh-1"></i>
        刷新
    </button>
    <button class="layui-btn layui-bg-blue layui-btn-md" lay-event="download">
        <i class="layui-icon layui-icon-export"></i>
        导出
    </button>
    <a id="exportReservation" download="预约数据.xlsx" style="display: none;"></a>
</script>

<script type="text/html" id="myReservation-bar">
    <button class="layui-btn  layui-btn-sm" lay-event="edit"><i
            class="layui-icon layui-icon-edit"></i>
    </button>
    <button class="layui-btn layui-btn-danger layui-btn-sm" sa:hasPermission="reservation_delete" lay-event="remove"><i
            class="layui-icon layui-icon-delete"></i>
    </button>
</script>
<script th:src="@{/pear/component/layui/layui.js}"></script>
<script th:src="@{/pear/component/pear/pear.js}"></script>
<script th:inline="javascript">
    layui.use(['table', 'form', 'jquery', 'laydate',], function () {
        let baseURL = /*[[@{/}]]*/ '';
        let table = layui.table;
        let laydate = layui.laydate;
        let form = layui.form;
        let $ = layui.jquery;
        laydate.render({
            elem: '#beginDate',
            type: 'date',//设置日期的类型
            theme: '#2c78da',
        })
        laydate.render({
            elem: '#endDateDiv',//绑定的控件名称
            type: 'date',//设置日期的类型
            theme: '#2c78da',
        })
        laydate.render({
            elem: "#timeFrame",
            type: "time",
            range: true,
            shortcuts: [
                {
                    text: '09:30 <p style="text-align: center;">到</p> 11:30',
                    value: (function () {
                        let date1 = new Date();
                        date1.setHours(9, 0, 0, 0);
                        let date2 = new Date();
                        date2.setHours(11, 30, 0, 0);
                        return [date1, date2];
                    })
                },
                {
                    text: '13:00 <p style="text-align: center;">到</p> 15:00',
                    value: (function () {
                        let date1 = new Date();
                        date1.setHours(13, 0, 0, 0);
                        let date2 = new Date();
                        date2.setHours(15, 0, 0, 0);
                        return [date1, date2];
                    })
                }
            ]
        });
        $.ajax({
            url: baseURL + 'meeting/reservation/getMeetByUserId', // 后端接口地址
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                var select = $('#meeting');
                select.empty().append('<option value="">请选择会议室</option>');
                let room = data.data
                $.each(room, function (index, rooms) {
                    select.append(
                        '<option value="' + rooms.roomId + '">' +
                        rooms.roomName +
                        '</option>'
                    );
                });
                form.render('select');
            },
            error: function () {
                layer.msg('加载失败', {icon: 2});
            }
        });
        let cols = [
            [{checkbox: true},
                {title: '主题', field: 'purpose', align: 'left',},
                {
                    title: '开始时间',
                    field: 'startTime',
                    align: 'left',
                    width: 200,
                    templet: function (d) {
                        return d.reservationData + ' ' + d.startTime;
                    }
                },
                {
                    title: '结束时间',
                    field: 'endTime',
                    align: 'left',
                    width: 200,
                    templet: function (d) {
                        return d.reservationData + ' ' + d.endTime;
                    }
                },
                {title: '会议室', field: 'roomName', align: 'left',},
                {title: '预约人', field: 'username', align: 'left',},
                {title: '预约人电话', field: 'phone', align: 'left',},
                {title: '操作', toolbar: '#myReservation-bar', align: 'center'}
            ]
        ]
        table.render({
            elem: '#myReservation-table',
            url: baseURL + 'meeting/reservation/list',
            request: {
                pageName: 'pageNum',
                limitName: 'pageSize'
            },
            type: 'get',
            page: true,
            curr: 1,
            cols: cols,
            skin: 'line',
            toolbar: '#myReservation-toolbar',
            limits: [5, 10, 15, 20],
            parseData: function (res) {// 对从后端获得的数据进行规范，最后返回四个键值对
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total,
                    "data": res.data.list, //解析数据列表
                };
            },
            response: {
                statusName: "code",
                msgName: "msg",
                statusCode: 1000,
                dataName: "data"
            },
        });

        table.on('tool(myReservation-table)', function (obj) {
            if (obj.event === 'remove') {
                window.remove(obj);
            } else if (obj.event === 'edit') {
                window.edit(obj)
            }
        });

        table.on('toolbar(myReservation-table)', function (obj) {
            if (obj.event === 'refresh') {
                window.refresh();
            } else if (obj.event === 'batchDelete') {
                window.batchDelete(obj);
            } else if (obj.event === 'download') {
                window.download(obj);
            }
        });

        form.on('submit(myReservation-query)', function () {
            let timeFrame = $('#timeFrame').val();
            let timeParts = timeFrame.split(' - ');
            let startTime = timeParts[0]; // 开始时间
            let endTime = timeParts[1];
            let roomName = $('#meeting').find('option:selected').text()
            if (roomName === "请选择会议室") {
                roomName = ""
            }
            let reservation = {
                purpose: $('#purpose').val(),
                reservationData: $('#beginDate').val(),
                startTime: startTime,
                endTime: endTime,
                repeatEndData: $('#endDateDiv').val(),
                roomName: roomName,
                repeatType: $('#repeatType').val()
            };
            table.reload('myReservation-table', {
                page: {
                    curr: 1
                },
                where: reservation
            });
            return false;
        });
        document.getElementById('resetBtn').addEventListener('click', function () {
            // 重新加载表格，不带任何过滤条件
            table.reload('myReservation-table', {
                where: {},
                page: {curr: 1} // 重新从第一页开始
            });
        });
        window.batchDelete = function (obj) {
            // 获取表格选中的行数据
            let checkStatus = table.checkStatus('myReservation-table');
            let reservationIds = checkStatus.data.map(function (row) {
                return row.reservationId; // 假设每行数据有个 reservationId 字段
            });
            console.log(reservationIds)
            // 检查是否有选中的记录
            if (reservationIds.length === 0) {
                layer.msg('请先选择要删除的记录', {
                    icon: 2,
                    time: 2000
                });
                return;
            }
            layer.confirm('确定要删除选中的记录吗？', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: baseURL + 'meeting/reservation/removeBatch',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(reservationIds),
                    success: function (result) {
                        layer.close(loading);
                        if (result.code === 1000) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 2000
                            }, function () {
                                table.reload('myReservation-table', {page: {curr: 1}});
                            });
                        } else {
                            layer.msg(result.msg, {
                                icon: 2,
                                time: 2000
                            });
                        }
                    }
                });
            });
        }
        window.download = function () {
            const exportLink = document.getElementById("exportReservation");
            exportLink.href = baseURL + `meeting/reservation/export?t=${Date.now()}`;

            // 触发点击事件
            exportLink.click();

            // 可选：显示导出提示
            alert("导出已开始，请稍候...");
        }
        window.edit = function (obj) {
            console.log(obj.data)
            window.reservationId = obj.data.reservationId;
            $.ajax({
                url: baseURL + 'department/session/getDepartmentId', // 后端接口地址
                type: 'get',
                contentType: 'application/json',
                success: function (response) {
                    $.ajax({
                        url: baseURL + 'user/getUserByDepartmentId?departmentId=' + response.data, // 后端接口地址
                        type: 'GET',
                        dataType: 'json',
                        success: function (res) {
                            layer.open({
                                type: 2,
                                title: '预约编辑',
                                shade: 0.1,
                                shadeClose: true,
                                area: ['600px', '400px'],
                                content: 'reservation-edit',
                                success: function (layero, index) {
                                    // 数据回显
                                    let body = layer.getChildFrame('body', index)
                                    let iframeWin = layero.find('iframe')[0].contentWindow;
                                    let data = obj.data
                                    var select = body.find('#username');
                                    select.empty().append('<option value="">请选择预约用户</option>');
                                    let user = res.data
                                    $.each(user, function (index, users) {
                                        select.append(
                                            '<option value="' + users.userId + '">' +
                                            users.username +
                                            '</option>'
                                        );
                                    });
                                    iframeWin.layui.form.render('select');
                                    body.find("input[name=purpose]").val(data.purpose)
                                    let users = 'dd[lay-value=' + data.userId + ']';
                                    body.find('#username').siblings("div.layui-form-select").find('dl').find(users).click();
                                }
                            })
                        },
                        error: function () {
                            layer.msg('加载失败', {icon: 2});
                        }
                    });
                }
            })
        }
        window.remove = function (obj) {
            layer.confirm('确定要删除该预约吗？', {
                icon: 3,
                title: '提示'
            }, function (index) {
                layer.close(index);
                let loading = layer.load();
                $.ajax({
                    url: baseURL + 'meeting/reservation/delete/' + obj.data['reservationId'],
                    dataType: 'json',
                    type: 'post',
                    success: function (result) {
                        layer.close(loading);
                        table.reload('myReservation-table', {page: {curr: 1}});
                        if (result.code === 1000) {
                            layer.msg(result.msg, {
                                icon: 1,
                                time: 2000
                            }, function () {

                            });
                        } else {
                            layer.msg(result.msg, {
                                icon: 2,
                                time: 2000
                            });
                        }
                    }
                });
            })
        }
        window.refresh = function () {
            table.reload('myReservation-table', {where: {}, page: {curr: 1}});
        }
    })
</script>
</body>
</html>
